package ru.acme.lab14.net;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class BankClient implements Runnable {
	private String serverName;
	private int port;

	public BankClient(String serverName, int port) {
		this.serverName = serverName;
		this.port = port;
	}

	public void run() {
		Socket socket;
		PrintStream socketOutputPrintStream;
		final Scanner socketScanner;
		try {
			socket = new Socket(serverName, port);
			socketOutputPrintStream = new PrintStream(socket.getOutputStream());
			socketScanner = new Scanner(socket.getInputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return;
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		new Thread(new Runnable() {
			public void run() {
				while (socketScanner.hasNext()) {
					String command = socketScanner.nextLine();
					System.out.println(command);
				}
			}
		}).start();
		Scanner consoleScanner = new Scanner(System.in);
		while (consoleScanner.hasNext()) {
			String command = consoleScanner.nextLine();
			socketOutputPrintStream.println(command);
			if (command.equals("exit")) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
				}
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}
		}
	}
	
}
